// 修改密码
import { editPasswordFn } from '@/api/login'
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

export function useEditPassword(){
    // 默认关闭修改密码对话框
    const dialogEditPwd = ref(false)
    // form表单dom元素
    const passwordFormRef = ref(null)
    // Form表单数据源
    const passwordForm = reactive({
        oldpassword: '',
        password: '',
        repassword: ''
    })
    // Form表单验证规则
    const passwordRules =  reactive({
        oldpassword: [
            {required: true, message: '请输入原密码', trigger: 'blur'},
            {min: 5, max: 15, message: '请输入5-15个字符', trigger: 'blur'}
        ],
       password: [
            {required: true, message: '请输入新密码', trigger: 'blur'},
            {min: 5, max: 15, message: '请输入5-15个字符', trigger: 'blur'}
        ],
        repassword: [
            {required: true, message: '请输入确认密码', trigger: 'blur'},
            {min: 5, max: 15, message: '请输入5-15个字符', trigger: 'blur'}
        ],
    
    })
    
    // 关闭修改密码对话框
    const closeHandle = () => {
        // 重置该表单项，将其值重置为初始值，并移除校验结果
        passwordFormRef.value.resetFields()
        
    }
    
    // 确定修改密码
    const editPwdHandle = () => {
        passwordFormRef.value.validate(async isValid => {
            if(!isValid) return 
            console.log(passwordForm)
            const res = await editPasswordFn(passwordForm)
            console.log(res)
            if(res.msg !== 'ok'){
                // 修改密码失败
                return ElMessage.error(res.msg)
            }
            ElMessage({
                message: '密码修改成功',
                type: 'success',
            })
            // 关闭对话框
            dialogEditPwd.value = false
        })
    }

    return {
        dialogEditPwd,
        passwordFormRef,
        passwordForm,
        passwordRules,
        closeHandle,
        editPwdHandle
    }
}


